<?php
/**
 * Created by MY_MIND.
 * User: WDJ
 * Date: 2018/7/5 0005
 * Time: 14:36
 */
namespace app\index\controller;

use \think\Config;
use \think\Controller;
use \think\Session;
use \think\Request;
use \think\Db;
use app\index\controller\Wechat;

use  app\index\model\Shopping;

class Shop extends Controller
{
    public $request;
    public $client_info;

    /**
     * Shop constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);

        //判断session是否存在client_info
        /*if(!Session::has('client_info')){
            $client_info        =   Db::name('relation')->where([ 'game_user_id' => Session::get('client_info.uid')])->find();//Session::get('client_info.uid')
            $this->client_info  =   $client_info ? array_merge($client_info , ['isBind' => true]): ['game_user_id' => 1, 'isBind' => false , 'invitation_code' => ''];
        }else{
           $this->handleData(600, '缺少参数');
        }*/
        if($jwt = input('jwt')){
            //分解jwt，然后保存session
            $arr = explode('.' , $jwt);
            if(hash_hmac('SHA256', $arr[0]. '.' .$arr[1], '8WhLBLP7suY') == $arr[2]){
                $info   =   json_decode(base64_decode($arr[1]), true);
                $client_info        =   Db::name('relation')->where([ 'game_user_id' =>$info['uid']])->field('game_user_id,invitation_code')->find();
                $this->client_info  =   $client_info ? array_merge($client_info , ['isBind' => true]) : ['game_user_id' => $info['uid'], 'isBind' => false , 'invitation_code' => ''];

                $data['uid']        =   $info['uid'];
                $data['type']       =   $info['type'];
                $data['isBind']     =   $this->client_info['isBind'];
                $data['code']       =   $this->client_info['invitation_code'];
                Session::set('client_info', $data);
            }else{
                $this->handleData(600, '缺少参数');
            }
        }

        /**
         * 如果没有jwt或者session的话就说明没有设置session
         */
        if(!input('jwt') && !Session::get('client_info')){
            $this->handleData(600, '缺少参数');
        }elseif(Session::get('client_info')){
            $client_info        =   Db::name('relation')->where([ 'game_user_id' => Session::get('client_info.uid')])->field('game_user_id,invitation_code')->find();
            $this->client_info  =   $client_info ? array_merge($client_info , ['isBind' => true]) : ['game_user_id' => Session::get('client_info.uid'), 'isBind' => false , 'invitation_code' => ''];
        }

        $this->request  =   Request::instance();
        if($this->request->isAjax()){
            //判断玩家是否存在
            if (!$this->request->post()['uid'] || !getSqlConnec('QPAccountsDB_CHUI', 'AccountsInfo')->where(['UserID' => $this->request->post()['uid']])->find()) {
                $this->handleData(1100, '玩家不存在');
            }

            if($this->request->action() != 'bindCode'){
                //判断玩家是否绑定邀请码
                if (!$this->request->post()['uid'] || !Db::name('relation')->where(['game_user_id' => $this->request->post()['uid']])->find()) {
                    $this->handleData(1000, '请绑定邀请码');
                }
            }
        }
    }

    /**
     * 返回JSON数据
     */
    protected  function handleData($code = 0, $result = '')
    {
        header('HTTP/1.1 200 OK');
        // 确保FastCGI模式下正常
        header('Status: 200 OK');
        header('Content-Type: application/json; charset=utf-8');
        exit(json_encode(['code' => $code, 'result' => $result]));
    }

    /**
     * 绑定邀请码
     */
    public function bindCode()
    {
        if($this->request->isAjax()){
            $model                  =   new Shopping();
            list($flag, $result)    =   $model->codeBind();
            if($flag){
                $this->handleData();
            }else{
                $this->handleData(800, $result);
            }
        }
    }

    /**
     * 请求商城旗力币显示并购买
     */
    public function showCoin()
    {
        if($this->request->isGet()){
            //查看套餐选项
            $result =   Db::name('price')->field('id,price,num')->select();

            $this->assign(['result' => $result, 'client_info' => $this->client_info]);
            return $this->fetch('shop/showCoin');
        }
    }

    /**
     * 请求商城房卡显示并购买
     */
    public function showCard()
    {
        if($this->request->isAjax()){
            //模型处理购买房卡操作
            $model                  =   new Shopping();
            list($flag, $result)    =   $model->buyCard();
            if($flag){
                $this->handleData();
            }else{
                $this->handleData(900, $result);
            }
        }else{
            //查看兑换比例
            $result =   Db::name('convert')->select();

            $this->assign(['result' => $result, 'client_info' => $this->client_info]);
            return $this->fetch('shop/showCard');
        }
    }

    /**
     * 请求商城卡包显示并购买
     */
    public function showPackage()
    {
        if($this->request->isAjax()){
            //模型处理购买房卡操作
            $model                  =   new Shopping();
            list($flag, $result)    =   $model->buyBag();
            if($flag){
                $this->handleData(0, $result);
            }else{
                $this->handleData(700, $result);
            }
        }else{
            //查看卡包详情
            $result =   Db::name('bag')->field('id, name, price, logo')->select();

            //查找游戏玩家的卡包剩余时间
            $end    =   getSqlConnec('QPTreasureDB_CHUI' , 'UserBackPack')->where(['UserID' => $this->client_info['game_user_id'] , 'GoodType' => 2])->order("DueTime desc")->limit(1)->find();
//            dump($end);
            //判断是否过期
            if($end && strtotime($end['DueTime']) > time()){
                $t['day'] =   date('Y/m/d', strtotime($end['DueTime']));
                $t['time']=   date('H:i', strtotime($end['DueTime']));
            }else{
                $t['day'] = '00/00/00';
                $t['time']= '00:00';
            }
            $this->assign(['result' => $result, 'client_info' => $this->client_info , 'time' => $t]);
            return $this->fetch('shop/showPackage');
        }
    }

    /**
     * 请求商城道具显示并购买
     */
    public function showProp()
    {
        if($this->request->isAjax()){
            //模型处理购买房卡操作
            $model                  =   new Shopping();
            list($flag, $result)    =   $model->buyTool();
            if($flag){
                $this->handleData();
            }else{
                $this->handleData(500, $result);
            }
        }else{
            //查看道具详情
            $result =   Db::name('goods')->where(['allow_buy' => 1 , 'style_type' => 1])->select();

            $this->assign(['result' => $result, 'client_info' => $this->client_info]);
            return $this->fetch('shop/showProp');
        }
    }

    /**
     * 发出h5支付请求
     * uid      游戏玩家ID
     * package  套餐ID
     */
    public function webPay()
    {
        //判断请求方式
        if($this->request->isAjax()){
            $this->config     =   Config::get('wxpay');
            $post       =   $this->request->post();
            //查看购买金额
            $coin       =   Db::name('price')->where(['id' => $post['package']])->find();
            if(!$coin){
                $this->handleData(300, '无效套餐');
            }

            $userInfo   =   getSqlConnec('QPAccountsDB_CHUI' , 'AccountsInfo')->where(['UserID' => $post['uid']])->find();
            if(!$userInfo){
                $this->handleData(900, '游戏玩家不存在');
            }

            $level      =   $userInfo['VIPLevel'] ? $userInfo['VIPLevel'] : 0;
            $discount   =   getSqlConnec('QPTreasureDB_CHUI' , 'VIPConfig')->where(['VIPLevel' => $level])->find()['DisCount'];
            $order_sn   =   'QA' . time() . createNoncestr(6);
            /**
             * 必传参数
             * appid    公众账号ID  mch_id  商户号 nonce_str   随机字符串   sign    签名
             * body     商品描述    out_trade_no    商户订单号   total_fee   总金额
             * spbill_create_ip 终端IP    notify_url  通知地址(不能带参数)
             * trade_type   交易类型(MWEB)  scene_info  场景信息(三种)
             * 1，IOS移动应用                                    2，安卓移动应用                                3，WAP网站应用
             * {"h5_info": //h5支付固定传"h5_info"          {"h5_info": //h5支付固定传"h5_info"               {"h5_info": //h5支付固定传"h5_info"
             * {"type": "IOS",  //场景类型                     {"type": "Android",  //场景类型                          {"type": "WAP",  //场景类型
             * "app_name": "",  //应用名                   "app_name": "",  //应用名                          "wap_url": "",//WAP网站URL地址
             * "bundle_id": ""  //bundle_id               "package_name": ""  //包名                         "wap_name": ""  //WAP 网站名
             * }                                          }                                                 }
             * }                                          }                                                }
             */
            //判断客户端类型
            $client_type                =   Session::get('client_info.type');
            if($client_type == 'IOS'){
                $h5_info_str            =   '{"h5_info": {"type":"IOS","app_name": "' . Config::get($client_type)['app_name'] . '","bundle_id": "' . Config::get($client_type)['bundle_id'] . '"}}';
                $device_type            =   1;
            }elseif($client_type == 'Android'){
                $h5_info_str            =   '{"h5_info": {"type":"Androiod","app_name": "' . Config::get($client_type)['app_name'] . '","package_name": "' . Config::get($client_type)['package_name'] . '"}}';
                $device_type            =   2;
            }else{
                $h5_info_str            =   '{"h5_info": {"type":"WAP","wap_url": "' . $this->request->domain() . $this->request->url(). '","wap_name": "' . '吹牛游戏商城' . '"}}';
                $device_type            =   3;
            }
            $weChat                     =   new Wechat();
            $data['appid']              =   $this->config['appid'];
            $data['mch_id']             =   $this->config['mch_id'];
            $data['nonce_str']          =   createNoncestr();
            $data['body']               =   '吹牛游戏商城';
            $data['out_trade_no']       =   $order_sn;
            $data['total_fee']          =   1;//intval(ceil($discount * $coin['price']) * 100);
            $data['spbill_create_ip']   =   $this->request->ip();
            $data['notify_url']         =   $this->request->domain() . url('index/Wechat/getWxpayRes');
            $data['trade_type']         =   'MWEB';
            $data['scene_info']         =   '{"h5_info": {"type":"WAP","wap_url": "' . $this->request->domain() . $this->request->url(). '","wap_name": "' . '吹牛游戏商城' . '"}}';
            $data['sign']               =   $weChat->getSign($data);
            //接口地址
            $url                        =   'https://api.mch.weixin.qq.com/pay/unifiedorder';
            //发出请求
            list($flag, $result)        =   curlQuery($url, 'POST', arrayToXml($data), true, ['CERT_PEM' => $this->config['cert_pem'] , 'KEY_PEM' => $this->config['key_pem']]);
            if(!$flag){
                $this->handleData(500, '请求错误');
            }
            $response_result            =   xmlToArray($result);
//            dump($response_result['return_code']);exit;
            //如果微信返回结果没有错的话直接接跳转到唤起微信支付的页面
            if($response_result['return_code'] == 'SUCCESS' && $response_result['result_code'] == 'SUCCESS'){
                //添加订单记录
                $log['uid']             =   $post['uid'];
                $log['order_sn']        =   $order_sn;
                $log['type']            =   1;      //购买旗力币类型
                $log['nums']            =   $coin['num'];
                $log['price']           =   $data['total_fee'];
                $log['is_rmb']          =   1;
                $log['is_pay']          =   0;
                $log['name']            =   '旗力币';
                $log['is_send']         =   0;
                $log['send_nums']       =   0;
                $log['create_time']     =   time();
                Db::name('shop_log')->insert($log);

                //请求成功后添加支付记录
                $pay['uid']             =   $post['uid'];
                $pay['appid']           =   $data['appid'];
                $pay['mch_id']          =   $data['mch_id'];
                $pay['ip_address']      =   $data['spbill_create_ip'];
                $pay['device_type']     =   $device_type;
                $pay['order_sn']        =   $order_sn;
                $pay['sign']            =   $data['sign'];
                $pay['total_nums']      =   $coin['num'];
                $pay['total_fee']       =   $data['total_fee'];
                $pay['status']          =   0;
                $pay['create_time']     =   time();

                $recordPayLog           =   Db::name('pay_log')->insert($pay);
                if($recordPayLog !== false){
                    //保存成功后跳转唤起的URL
                    $this->handleData(0, $response_result['mweb_url']);
                }
            }elseif($response_result['result_code'] == 'FAIL'){
                $this->handleData($response_result['err_code'], $response_result['err_code_des']);
            }

        }
    }

}
